using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Runtime.Serialization;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using LynxWebLog.ViewModels;

namespace LynxWebLog.Controllers
{
    [Authorize(Roles = "BlogUser,BlogAdmin")]
    public class BlogDataController : Controller
    {

        List<BlogData> _lbd = new List<BlogData>();
        HttpClient client = ClientUtility.BlogAPIClient();
        //
        // GET: /BlogData/
        public async Task<ActionResult> Index()
        {
            ViewBag.Version = " v: " + Assembly.GetExecutingAssembly().GetName().Version;
            try {
                HttpResponseMessage resp = await client.GetAsync("api/BlogData/?$filter=username eq '" + User.Identity.Name + "'");
                resp.EnsureSuccessStatusCode();

                IEnumerable<BlogData> bd = await resp.Content.ReadAsAsync<IEnumerable<BlogData>>();
                _lbd = bd.ToList();
            }
            catch (SerializationException ex) {
                Debug.Print(ex.Message);
            }
            catch (HttpRequestException ex) {
                Debug.Print(ex.Message);
            }

            return View(_lbd);
        }

        //
        // GET: /BlogData/Details/5
        public async Task<ActionResult> Details(string id)
        {
            ViewBag.Version = " v: " + Assembly.GetExecutingAssembly().GetName().Version;
            BlogDataView bdv = new BlogDataView();
            try {
                HttpResponseMessage resp = await client.GetAsync("api/BlogData/?$filter=username eq '" + User.Identity.Name + "' and blogid eq '" + id + "'");
                resp.EnsureSuccessStatusCode();

                bdv.bd = (await resp.Content.ReadAsAsync<IEnumerable<BlogData>>()).FirstOrDefault();

                resp = await client.GetAsync("api/CommentPolicy/?$filter blogid eq '" + id + "'");
                resp.EnsureSuccessStatusCode();

                bdv.cp = (await resp.Content.ReadAsAsync<IEnumerable<CommentPolicy>>()).FirstOrDefault();
                if (bdv.cp == null) {
                    bdv.cp = new CommentPolicy();
                    bdv.cp.blogid = bdv.bd.blogid;
                }
            }
            catch (SerializationException ex) {
                Debug.Print(ex.Message);
            }
            catch (HttpRequestException ex) {
                Debug.Print(ex.Message);
            }
            return View(bdv);
        }

        //
        // GET: /BlogData/Create
        public ActionResult Create()
        {
            ViewBag.Version = " v: " + Assembly.GetExecutingAssembly().GetName().Version;
            ViewBag.License = CC_License.BuildLicenseFlds(string.Empty, this.HttpContext);
            return View();
        }

        //
        // POST: /BlogData/Create
        [HttpPost]
        [ValidateAntiForgeryToken]
        [MaliciousActivityChecksFilter]
        public async Task<ActionResult> Create(BlogDataView bdv)
        {
            ViewBag.Version = " v: " + Assembly.GetExecutingAssembly().GetName().Version;
            ViewBag.License = CC_License.BuildLicenseFlds(string.Empty, this.HttpContext);
            if (ModelState.IsValid) {
                try {
                    string userPath = Server.MapPath("~/BlogResources/" + bdv.bd.username);
                    DirectoryInfo di = new DirectoryInfo(userPath);
                    if (!di.Exists) {
                        di.Create();
                    }
                    string blogPath = Path.Combine(userPath, bdv.bd.blogname);
                    DirectoryInfo dBlog = new DirectoryInfo(blogPath);
                    if (!dBlog.Exists) {
                        dBlog.Create();
                    }
                    HttpResponseMessage resp = await client.PostAsXmlAsync("api/BlogData", bdv.bd);
                    resp.EnsureSuccessStatusCode();

                    resp = await client.PostAsXmlAsync("api/CommentPolicy", bdv.cp);
                    resp.EnsureSuccessStatusCode();

                    return RedirectToAction("Index");
                }
                catch (SystemException ex) {
                    Debug.Print(ex.Message);
                    //return View();
                }
            }
            return View();
        }

        //
        // GET: /BlogData/Edit/5
        public async Task<ActionResult> Edit(string id)
        {
            ViewBag.Version = " v: " + Assembly.GetExecutingAssembly().GetName().Version;
            BlogDataView bdv = new BlogDataView();
            try {
                HttpResponseMessage resp = await client.GetAsync("api/BlogData/?$filter=username eq '" + User.Identity.Name + "' and blogid eq '" + id + "'");
                resp.EnsureSuccessStatusCode();

                bdv.bd = (await resp.Content.ReadAsAsync<IEnumerable<BlogData>>()).FirstOrDefault();
                
                resp = await client.GetAsync("api/CommentPolicy/?$filter blogid eq '" + id + "'");
                resp.EnsureSuccessStatusCode();

                bdv.cp = (await resp.Content.ReadAsAsync<IEnumerable<CommentPolicy>>()).FirstOrDefault();
                if (bdv.cp == null) {
                    bdv.cp = new CommentPolicy();
                    bdv.cp.blogid = bdv.bd.blogid;
                }
            }
            catch (SystemException ex) {
                Debug.Print(ex.Message);
            }
            ViewBag.License = CC_License.BuildLicenseFlds(bdv.bd.license, this.HttpContext);
            return View(bdv);
        }

        //
        // POST: /BlogData/Edit/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        [MaliciousActivityChecksFilter]
        public async Task<ActionResult> Edit(BlogDataView bdv)
        {
            ViewBag.Version = " v: " + Assembly.GetExecutingAssembly().GetName().Version;
            try
            {
                HttpResponseMessage resp = await client.PutAsXmlAsync("api/BlogData/" + bdv.bd.blogid, bdv.bd);
                resp.EnsureSuccessStatusCode();

                if (bdv.cp == null) {
                    bdv.cp = new CommentPolicy();
                    bdv.cp.blogid = bdv.bd.blogid;
                }

                resp = await client.PutAsXmlAsync("api/CommentPolicy/" + bdv.cp.blogid, bdv.cp);
                resp.EnsureSuccessStatusCode();

                return RedirectToAction("Index");
            }
            catch (SystemException ex)
            {
                Debug.Print(ex.Message);
                ViewBag.License = CC_License.BuildLicenseFlds(bdv.bd.license, this.HttpContext);
                return View(bdv);
            }
        }

        //
        // GET: /BlogData/Delete/5
        public async Task<ActionResult> Delete(string id)
        {
            ViewBag.Version = " v: " + Assembly.GetExecutingAssembly().GetName().Version;
            BlogData bd = new BlogData();
            try {
                HttpResponseMessage resp = await client.GetAsync("api/BlogData/?$filter=username eq '" + User.Identity.Name + "' and blogid eq '" + id + "'");
                resp.EnsureSuccessStatusCode();

                bd = (await resp.Content.ReadAsAsync<IEnumerable<BlogData>>()).FirstOrDefault();
            }
            catch (SystemException ex) {
                Debug.Print(ex.Message);
            }
            return View(bd);
        }

        //
        // POST: /BlogData/Delete/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        [MaliciousActivityChecksFilter]
        public async Task<ActionResult> DeleteConfirmed(string blogid)
        {
            try
            {
                HttpResponseMessage resp = await client.DeleteAsync("api/BlogData/" + blogid);
                resp.EnsureSuccessStatusCode();

                resp = await client.DeleteAsync("api/CommentPolicy/" + blogid);
                resp.EnsureSuccessStatusCode();

                return RedirectToAction("Index");
            }
            catch (SystemException ex)
            {
                Debug.Print(ex.Message);
                return RedirectToAction("Delete");
            }
        }

    }
}
